export default {
  // json 字符串转表单
  getFormData(requestParams) {
    const obj = JSON.parse(requestParams)
    return this.getFormData2(obj)
  },
  getFormData2(obj) {
    return this.getFormDataToJson(obj)
  },
  getJsonObj(requestParams) {
    return JSON.parse(requestParams)
  },
  getFormDataToJson(obj) {
    const formData = new FormData()
    // 拿到json对象获取对象内所有的key
    Object.keys(obj).forEach(key => {
      const objElement = obj[key]
      // 判断key所对应的val是不是数组
      if (obj[key] instanceof Array) {
        var objElement1 = obj[key]
        // 遍历写值到FormData里去
        for (let i = 0; i < objElement1.length; i++) {
          if (Object.prototype.toString.call(objElement1[i]) === '[object Object]') {
            this.recursive(formData, key, i, objElement1[i])
          } else {
            formData.append(`${key}[${i}]`, objElement1[i])
          }
        }
      }
      // 如果是对象 则遍历key继续写值
      if (Object.prototype.toString.call(objElement) === '[object Object]') {
        this.recursive(formData, key, null, objElement)
      } else {
        // 什么也不是，直接写入 formData
        if (!(obj[key] instanceof Array)) {
          formData.append(key, obj[key])
        }
      }
    })
    return formData
  },
  recursive(formData, k, num, obj) {
    // 递归 和上面同理
    Object.keys(obj).forEach(key => {
      const objElement = obj[key]
      if (Object.prototype.toString.call(objElement) === '[object Object]') {
        this.recursive(formData, `${k}[${num}].${key}`, null, objElement)
      } else {
        if (num != null) {
          const str = `${k}[${num}].${key}`
          if (obj[key] instanceof Array) {
            var objElement2 = obj[key]
            for (let i = 0; i < objElement2.length; i++) {
              if (Object.prototype.toString.call(objElement2[i]) === '[object Object]') {
                this.recursive(formData, str, i, objElement2[i])
              }
            }
          } else {
            formData.append(str, obj[key])
          }
        } else {
          const str = `${k}.${key}`
          formData.append(str, obj[key])
        }
      }
    })
  }
}

